package utils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"fmt"
	"strings"
	"time"
)

// EncodeShortCode EncodeShortCode
func EncodeShortCode(id, salt int64) (code string) {
	length := int64(len(shortRunes))
	num := id + salt
	var checksum int64
	for num > 0 {
		idx := num % length
		num = num / length
		checksum += idx
		code = fmt.Sprintf("%s%s", string(shortRunes[idx]), code)
	}
	if id+salt > length {
		idx := checksum % length
		code = fmt.Sprintf("%s%s", code, string(shortRunes[idx]))
	}
	return
}

// DecodeShortCode DecodeShortCode
func DecodeShortCode(salt int64, code string) (id int64) {
	code = strings.ToUpper(code)
	length := int64(len(shortRunes))
	passwordMap := make(map[rune]int, length)
	for i, r := range shortRunes {
		passwordMap[r] = i
	}
	var num, checksum int64
	count := len(code)
	if count > 1 {
		count--
		for _, s := range code[:count] {
			num *= length
			if char, isExist := runeMap[s]; isExist {
				s = char
			}
			if _, isExist := passwordMap[s]; !isExist {
				id = 0
				return
			}
			idx := int64(passwordMap[s])
			num += idx
			checksum += idx
		}
		idx := checksum % length
		checksumRune := rune(code[count])
		checksum = int64(passwordMap[checksumRune])
		if idx != checksum {
			num = salt
		}
	} else {
		for _, s := range code {
			idx := int64(passwordMap[s])
			num += idx
		}
	}
	id = num - salt
	return
}

const cMagicNum int64 = 10000000000

func getElapsedSeconds() (seconds int64) {
	start := time.Date(2018, time.January, 1, 0, 0, 0, 0, time.UTC)
	seconds = int64(time.Since(start).Seconds())
	return
}

// EncodeMagicNum EncodeMagicNum
func EncodeMagicNum(val int64) (num int64) {
	num = (val * cMagicNum) + cMagicNum - (getElapsedSeconds() % cMagicNum)
	return
}

// DecodeMagicNum DecodeMagicNum
func DecodeMagicNum(num int64) (val int64) {
	val = num / cMagicNum
	return
}

func EncryptUserInfo(userinfo []byte, secret string) (dest string, err error) {
	var cryptedBytes []byte
	cryptedBytes, err = AesEncrypt(userinfo, []byte(secret))
	if err != nil {
		return
	}
	return base64.StdEncoding.EncodeToString(cryptedBytes), nil
}

func DecryptUserInfo(dest, secret string) (userInfo []byte, err error) {
	decoded, err := base64.StdEncoding.DecodeString(dest)
	if err != nil {
		return
	}
	return AesDecrypt(decoded, []byte(secret))
}

func EncryptFlowerGift(userinfo []byte, secret string) (dest string, err error) {
	var cryptedBytes []byte
	cryptedBytes, err = AesEncrypt(userinfo, []byte(secret))
	if err != nil {
		return
	}
	return base64.RawURLEncoding.EncodeToString(cryptedBytes), nil
}

func DecryptFlowerGift(dest, secret string) (userInfo []byte, err error) {
	decoded, err := base64.RawURLEncoding.DecodeString(dest)
	if err != nil {
		return
	}
	return AesDecrypt(decoded, []byte(secret))
}

func AesEncrypt(origData, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	origData = PKCS5Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

func AesDecrypt(crypted, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	return origData, nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unpadding 次
	unpadding := int(origData[length-1])
	if unpadding > length {
		return nil
	}
	return origData[:(length - unpadding)]
}
